package com.example.ssmxuankeback.config;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
@WebFilter(filterName = "CORSFilter")
public class CORSFilter implements Filter {
    /**
     * 跨域实现，即让服务器同意跨域请求
     * */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 允许跨域请求，填*表示全部，Origin表示谁请求我就允许谁跨域，这次请求以后都允许
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
        // 允许携带cookie，默认值是false
        response.setHeader("Access-Control-Allow-Credentials","true");
        // 表示哪些方法的请求是可以的
        response.setHeader("Access-Control-Allow-Methods","POST,GET,PATCH,DELETE,PUT");
        // 设置最长缓存时间
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");

        // 让过滤链继续
        filterChain.doFilter(request,response);
    }
}
